// 历史趋势图相关变量
let historicalChart = null;

// 苹果风格的颜色 - 与主图表一致
const colors = {
  blue: "#0071e3",
  lightBlue: "#42a1ec",
  green: "#34c759",
  red: "#ff3b30",
  yellow: "#ffcc00",
  purple: "#5e5ce6",
  gray: "#8e8e93",
  orange: "#ff9500",
};

// 产品颜色配置 - 与主图表保持一致
const productColors = {
  总计: colors.blue,
  素材神器: colors.blue,
  推文神器: colors.green,
  追爱神器: colors.red,
  爱帮主: colors.purple,
  AI情话: colors.orange,
  追爱神器: "#ff2d92",
};

// 初始化历史趋势图
function initHistoricalChart() {
  try {
    // 直接使用传递的数据初始化
    if (typeof historicalChartData !== "undefined") {
      createHistoricalChart(historicalChartData);
    } else {
      console.error("历史数据未加载");
      return;
    }

    // 设置周期选择器事件
    const periodSelector = document.getElementById("historyPeriod");
    if (periodSelector) {
      periodSelector.addEventListener("change", function (e) {
        const days = parseInt(e.target.value);
        const filteredData = filterHistoricalData(historicalChartData, days);
        createHistoricalChart(filteredData);
      });
    }
  } catch (error) {
    console.error("初始化历史趋势图失败:", error);
  }
}

// 过滤历史数据（根据天数）
function filterHistoricalData(data, days) {
  if (!data || !data.dates) {
    return data;
  }

  if (days >= data.dates.length) {
    return data;
  }

  const startIndex = Math.max(0, data.dates.length - days);
  const filteredData = {
    dates: data.dates.slice(startIndex),
    products: data.products,
    data: {},
  };

  // 过滤每个产品的数据
  for (const key in data.data) {
    if (data.data.hasOwnProperty(key)) {
      filteredData.data[key] = data.data[key].slice(startIndex);
    }
  }

  return filteredData;
}

// 创建历史趋势图
function createHistoricalChart(data) {
  const ctx = document.getElementById("historicalChart");
  if (!ctx || !data) return;

  // 如果图表已存在，先销毁
  if (historicalChart) {
    historicalChart.destroy();
  }

  // 准备数据集
  const datasets = [];

  // 添加日均流水线（使用已有的warningValue）
  if (typeof warningValue !== "undefined" && warningValue > 0) {
    const avgLineData = new Array(data.dates.length).fill(warningValue);
    datasets.push({
      label: "日均",
      data: avgLineData,
      borderColor: colors.red,
      backgroundColor: "rgba(255, 59, 48, 0)",
      borderWidth: 1.5,
      borderDash: [3, 5],
      fill: false,
      pointRadius: 0,
      pointHoverRadius: 0,
      hidden: false,
    });
  }

  // 添加总计数据（默认显示）
  if (data.data["总计"]) {
    datasets.push({
      label: "总计",
      data: data.data["总计"],
      borderColor: productColors["总计"],
      backgroundColor: "rgba(0, 113, 227, 0.05)",
      borderWidth: 2,
      fill: true,
      tension: 0.3,
      pointRadius: 0.5,
      pointHoverRadius: 3,
      pointBackgroundColor: "#ffffff",
      pointBorderColor: productColors["总计"],
      pointBorderWidth: 1,
      hidden: false,
    });
  }

  // 添加各产品数据（默认隐藏）
  if (data.products) {
    data.products.forEach(function (product) {
      const color = productColors[product] || getRandomColor();
      datasets.push({
        label: product,
        data: data.data[product],
        borderColor: color,
        backgroundColor: hexToRgba(color, 0),
        borderWidth: 1.5,
        fill: false,
        tension: 0.3,
        pointRadius: 0,
        pointHoverRadius: 3,
        pointBackgroundColor: "#ffffff",
        pointBorderColor: color,
        pointBorderWidth: 1,
        hidden: true, // 默认隐藏各产品线
      });
    });
  }

  // 创建图表
  historicalChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: data.dates.map(function (date) {
        return formatDate(date);
      }),
      datasets: datasets,
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      layout: {
        padding: {
          top: 15,
          right: 15,
          bottom: 50,
          left: 15,
        },
      },
      interaction: {
        mode: "index",
        intersect: false,
      },
      animation: {
        duration: 1000,
        easing: "easeOutQuart",
      },
      plugins: {
        legend: {
          display: true,
          position: "top",
          align: "end",
          labels: {
            boxWidth: 3,
            boxHeight: 3,
            usePointStyle: true,
            pointStyle: "circle",
            padding: 15,
            color: "#1d1d1f",
            font: {
              family:
                "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
              size: 12,
              weight: "500",
            },
            generateLabels: function (chart) {
              const original =
                Chart.defaults.plugins.legend.labels.generateLabels;
              const labels = original.call(this, chart);

              // 为总计标签添加特殊样式
              labels.forEach(function (label) {
                if (label.text === "总计") {
                  label.fontStyle = "bold";
                }
              });

              return labels;
            },
          },
          onClick: function (e, legendItem, legend) {
            const index = legendItem.datasetIndex;
            const ci = legend.chart;
            const dataset = ci.data.datasets[index];

            // 切换数据集的显示状态
            dataset.hidden = !dataset.hidden;
            ci.update();
          },
        },
        tooltip: {
          backgroundColor: "rgba(255, 255, 255, 0.95)",
          titleColor: "#1d1d1f",
          bodyColor: "#1d1d1f",
          borderColor: "rgba(0, 0, 0, 0.1)",
          borderWidth: 1,
          cornerRadius: 8,
          padding: 12,
          boxPadding: 6,
          usePointStyle: true,
          titleFont: {
            family:
              "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
            size: 13,
            weight: "600",
          },
          bodyFont: {
            family:
              "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
            size: 12,
            weight: "400",
          },
          footerFont: {
            family:
              "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
            size: 11,
            weight: "400",
          },
          callbacks: {
            title: function (context) {
              return context[0].label;
            },
            label: function (context) {
              const value = context.parsed.y;
              return context.dataset.label + ": " + formatValue(value);
            },
          },
        },
      },
      scales: {
        x: {
          display: true,
          title: {
            display: false,
          },
          grid: {
            color: "rgba(0, 0, 0, 0.05)",
            borderColor: "rgba(0, 0, 0, 0.1)",
            drawBorder: true,
          },
          ticks: {
            display: true,
            color: "#8e8e93",
            font: {
              family:
                "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
              size: 11,
              weight: "400",
            },
            maxTicksLimit: 8,
            padding: 10,
          },
          border: {
            display: true,
            color: "rgba(0, 0, 0, 0.1)",
          },
        },
        y: {
          display: true,
          title: {
            display: false,
          },
          grid: {
            color: "rgba(0, 0, 0, 0.05)",
            borderColor: "rgba(0, 0, 0, 0.1)",
          },
          ticks: {
            color: "#8e8e93",
            font: {
              family:
                "SF Pro Display, -apple-system, BlinkMacSystemFont, sans-serif",
              size: 11,
              weight: "400",
            },
            callback: function (value) {
              return formatValueSimple(value);
            },
          },
        },
      },
    },
  });
}

// 格式化值（显示具体数字with千位分隔符）
function formatValue(value) {
  return new Intl.NumberFormat("zh-CN").format(value);
}

// 格式化值（简化显示，类似实时图表）
function formatValueSimple(value) {
  if (value >= 10000) {
    return Math.round(value / 10000) + "万";
  } else if (value >= 1000) {
    return Math.round(value / 1000) + "千";
  } else {
    return Math.round(value).toString();
  }
}

// 格式化日期
function formatDate(dateStr) {
  const date = new Date(dateStr);
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return month + "/" + day;
}

// 获取随机颜色
function getRandomColor() {
  const colorValues = Object.values(colors);
  return colorValues[Math.floor(Math.random() * colorValues.length)];
}

// 十六进制颜色转RGBA
function hexToRgba(hex, alpha) {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
}

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", function () {
  // 等待一下确保数据已经加载
  setTimeout(function () {
    initHistoricalChart();
  }, 100);
});
